﻿using System;


namespace DotNetNuke.Tests.UI.WatiN.Utilities
{
    using System.IO;
    using System.Xml;
    using System.Xml.Linq;
    using System.Linq;
    using System.Xml.XPath;

    using Common;

    using Services.Installer;

    public static class WebConfigManager
    {
        public static void UpdateConfig(string physicalPath)
        {
            var mailDropFragment = XDocument.Load(Path.Combine(TestEnvironment.TestFilesPath, "mailDrop.xml"));
            var specifiedPickupDirectory = mailDropFragment.XPathSelectElement("configuration/nodes/node/system.net/mailSettings/smtp/specifiedPickupDirectory");
            specifiedPickupDirectory.Attribute("pickupDirectoryLocation").Value = TestEnvironment.TestEmailPath;
            mailDropFragment.Save(Path.Combine(TestEnvironment.PackagePath, "UpdatedMailDrop.xml"));
            var mailDrop = new FileStream(Path.Combine(TestEnvironment.PackagePath, "UpdatedMailDrop.xml"), FileMode.Open, FileAccess.Read);
            try
            {
                var fileName = string.Format("{0}\\web.config", physicalPath);
                var targetDocument = new XmlDocument();
                targetDocument.Load(fileName);
                var mailNodes = (from mail in targetDocument.DocumentElement.ChildNodes.Cast<XmlNode>()
                                 where mail.Name == "system.net"
                                 select mail).ToList();
                if (mailNodes.Count == 0)
                {
                    var merge = new XmlMerge(mailDrop, String.Empty, String.Empty);
                    merge.UpdateConfig(targetDocument);
                    targetDocument.Save(fileName);
                }
            }
            finally
            {
                mailDrop.Close();
            }
        }
    }
}
